package cn.xshi.gateway.route.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.CharsetUtil;
import cn.xshi.gateway.route.client.vo.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
 * @Desc 网关路由 Netty客户端工具类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
@Component
public class GatewayNettyClientUtil {
    /**
     * 发送消息
     * @param channel
     * @param requestInfo
     * @return
     */
    public boolean sendMessage(Channel channel,RequestInfo requestInfo){
        boolean result = true;
        try {
            if(null == channel){
                log.info("未能获取到网关路由通道");
                result = false;
            }else{
                String json = JSONObject.toJSONString(requestInfo);
                //创建一个持有数据的ByteBuf
                ByteBuf buf = Unpooled.copiedBuffer(json, CharsetUtil.UTF_8);
                //数据冲刷
                ChannelFuture cf = channel.writeAndFlush(buf);
                //添加ChannelFutureListener以便在写操作完成后接收通知
                cf.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()){
                            log.info("网关路由与路由服务握手成功...");
                        }else{
                            log.info("网关路由与路由服务握手失败...");
                            future.cause().printStackTrace();
                        }
                    }
                });
            }
        }catch (Exception e){
            log.error("发送网关路由消息异常：",e);
            result =  false;
        }
        return result;
    }
}
